<?php

// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: huajie <banhuajie@163.com>
// +----------------------------------------------------------------------

namespace Admin\Controller;

use Admin\Model\AuthGroupModel;
use Think\Page;
use User\Api\UserApi;

/**
 * 後臺內容控制器
 * @author huajie <banhuajie@163.com>
 */
class ArticleController extends AdminController {
    /* 保存允許訪問的公共方法 */

    static protected $allow = array('draftbox', 'mydocument');
    private $cate_id = null; //文檔分類id

    /**
     * 檢測需要動態判斷的文檔類目有關的權限
     *
     * @return boolean|null
     *      返回true則表示當前訪問有權限
     *      返回false則表示當前訪問無權限
     *      返回null，則會進入checkRule根據節點授權判斷權限
     *
     * @author 朱亞傑  <xcoolcc@gmail.com>
     */

    protected function checkDynamic() {
        if (IS_ROOT) {
            return true; //管理員允許訪問任何頁面
        }
        $cates = AuthGroupModel::getAuthCategories(UID);
        switch (strtolower(ACTION_NAME)) {
            case 'index':   //文檔列表
                $cate_id = I('cate_id');
                break;
            case 'edit':    //編輯
            case 'update':  //更新
                $doc_id = I('id');
                $cate_id = M('Document')->where(array('id' => $doc_id))->getField('category_id');
                break;
            case 'setstatus': //更改狀態
            case 'permit':    //回收站
                $doc_id = (array) I('ids');
                $cate_id = M('Document')->where(array('id' => array('in', $doc_id)))->getField('category_id', true);
                $cate_id = array_unique($cate_id);
                break;
        }
        if (!$cate_id) {
            return null; //不明,需checkRule
        } elseif (!is_array($cate_id) && in_array($cate_id, $cates)) {
            return true; //有權限
        } elseif (is_array($cate_id) && $cate_id == array_intersect($cate_id, $cates)) {
            return true; //有權限
        } else {
            return false; //無權限
        }
        return null; //不明,需checkRule
    }

    /**
     * 顯示左邊菜單，進行權限控制
     * @author huajie <banhuajie@163.com>
     */
    protected function getMenu() {
        //獲取動態分類
        $cate_auth = AuthGroupModel::getAuthCategories(UID); //獲取當前用戶所有的內容權限節點
        $cate_auth = $cate_auth == null ? array() : $cate_auth;
        $cate = M('Category')->where(array('status' => 1,'show'=>1))->field('id,title,pid,allow_publish')->order('pid,sort')->select();

        //沒有權限的分類則不顯示
        if (!IS_ROOT) {
            foreach ($cate as $key => $value) {
                if (!in_array($value['id'], $cate_auth)) {
                    unset($cate[$key]);
                }
            }
        }

        $cate = list_to_tree($cate); //生成分類樹
        //獲取分類id
        $cate_id = I('param.cate_id');
        $this->cate_id = $cate_id;

        //是否展開分類
        $hide_cate = false;
        if (ACTION_NAME != 'recycle' && ACTION_NAME != 'draftbox' && ACTION_NAME != 'mydocument') {
            $hide_cate = true;
        }

        //dump($cate);die;
        //生成每個分類的url
        foreach ($cate as $key => &$value) {
            if($value['id']=='40'||$value['id']=='47'){
                $datas=D('Document')->lists($value['id']);
                
                $value['url'] = 'Article/edit?id='.$datas[0]['id'].'&model='.$datas[0]['model_id'].'&cate_id=' . $value['id'];
            }  else {
                 $value['url'] = 'Article/index?cate_id=' . $value['id'];
            }     
            //$value['url'] = 'Article/index?cate_id=' . $value['id'];
            if ($cate_id == $value['id'] && $hide_cate) {
                $value['current'] = true;
            } else {
                $value['current'] = false;
            }
            if (!empty($value['_child'])) {
                $is_child = false;
                foreach ($value['_child'] as $ka => &$va) {
                    if($va['id']=='49'||$va['id']=='50'||$va['id']=='51'||$va['id']=='72'){
                        $datava=D('Document')->lists($va['id']);
                        $va['url'] = 'Article/edit?id='.$datava[0]['id'].'&model='.$datava[0]['model_id'].'&cate_id=' . $va['id'];
                    }else{
                        $va['url'] = 'Article/index?cate_id=' . $va['id'];
                    }
                    if (!empty($va['_child'])) {
                        foreach ($va['_child'] as $k => &$v) {
                            $v['url'] = 'Article/index?cate_id=' . $v['id'];
                            $v['pid'] = $va['id'];
                            $is_child = $v['id'] == $cate_id ? true : false;
                        }
                    }
                    //展開子分類的父分類
                    if ($va['id'] == $cate_id || $is_child) {
                        $is_child = false;
                        if ($hide_cate) {
                            $value['current'] = true;
                            $va['current'] = true;
                        } else {
                            $value['current'] = false;
                            $va['current'] = false;
                        }
                    } else {
                        $va['current'] = false;
                    }
                }
            }
        }
        //dump($cate);die;
        $this->assign('nodes', $cate);
        $this->assign('cate_id', $this->cate_id);
       

        //獲取面包屑信息
        $nav = get_parent_category($cate_id);
        $this->assign('rightNav', $nav);

        //獲取回收站權限
        $show_recycle = $this->checkRule('Admin/article/recycle');
        $this->assign('show_recycle', IS_ROOT || $show_recycle);
        //獲取草稿箱權限
        $this->assign('show_draftbox', C('OPEN_DRAFTBOX'));
    }

    /**
     * 分類文檔列表頁
     * @param $cate_id 分類id
     * @author 朱亞傑 <xcoolcc@gmail.com>
     */
    public function index($cate_id = null) {
        //獲取左邊菜單
        $this->getMenu();

        if ($cate_id === null) {
            $cate_id = $this->cate_id;
        }

        
        
        //獲取模型信息
        $model = M('Model')->getByName('document');

        //解析列表規則
        $fields = array();
        $grids = preg_split('/[;\r\n]+/s', $model['list_grid']);
        foreach ($grids as &$value) {
            // 字段:標題:鏈接
            $val = explode(':', $value);
            // 支持多個字段顯示
            $field = explode(',', $val[0]);
            $value = array('field' => $field, 'title' => $val[1]);
            if (isset($val[2])) {
                // 鏈接信息
                $value['href'] = $val[2];
                // 搜索鏈接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function($match) use(&$fields) {
                    $fields[] = $match[1];
                }, $value['href']);
            }
            if (strpos($val[1], '|')) {
                // 顯示格式定義
                list($value['title'], $value['format']) = explode('|', $val[1]);
            }
            foreach ($field as $val) {
                $array = explode('|', $val);
                $fields[] = $array[0];
            }
        }

        // 過濾重復字段信息 TODO: 傳入到查詢方法
        $fields = array_unique($fields);

        //獲取對應分類下的模型
        if (!empty($cate_id)) {   //沒有權限則不查詢數據
            //獲取分類綁定的模型
            $models = get_category($cate_id, 'model');
            $allow_reply = get_category($cate_id, 'reply'); //分類文檔允許回復
            $pid = I('pid');
          
            if ($pid == 0) {
                //開發者可根據分類綁定的模型,按需定制分類文檔列表
                $template = $this->indexOfArticle($cate_id); //轉入默認文檔列表方法

                $this->assign('model', explode(',', $models)); 
                
            } else {
                //開發者可根據父文檔的模型類型,按需定制子文檔列表
                $doc_model = M('Document')->where(array('id' => $pid))->find();                
                switch ($doc_model['model_id']) {
                    default:
                        if ($doc_model['type'] == 2 && $allow_reply) {
                            $this->assign('model', array(2));
                            $template = $this->indexOfReply($cate_id); //轉入子文檔列表方法
                        } else {
                            $this->assign('model', explode(',', $models));
                            $template = $this->indexOfArticle($cate_id); //轉入默認文檔列表方法
                        }
                }
            }

                        //檢查是否使用自定義列表模板
            $doc_model = M('Model')->where(array('id' => $models))->find();
            
            
            if(!empty($doc_model['template_list']))
            {
                $template = 'Think/'.$doc_model['template_list'];
                
           
                //echo $template;
                $data = D('Document')->listpage($cate_id,15);
               
                $this->assign('list', $data['data2']);
                $this->assign('_page', $data['data1']);
                $this->assign('list_grids', $grids);
                $this->assign('model_list', $model);
          
               
            }
            else
            {   
                if($cate_id=='67'){
                    $lists=D('Document')->lists(62);                
                     $this->assign(listss, $lists);               
                 }elseif($cate_id=='70'){
                    $lists=D('Document')->lists(63);               
                     $this->assign(listss, $lists);
                }else if($cate_id=='66'){
                   
                    
                }
                $this->assign('list_grids', $grids);
                $this->assign('model_list', $model);
            }
            // 記錄當前列表頁的cookie
       
           
            Cookie('__forward__', $_SERVER['REQUEST_URI']);
            
           // echo $template;
            
            $this->display($template);
            
            
        } else {
            $this->error('非法的文檔分類');
        }
    }

    /**
     * 默認文檔回復列表方法
     * @param $cate_id 分類id
     * @author huajie <banhuajie@163.com>
     */
    protected function indexOfReply($cate_id) {
        /* 查詢條件初始化 */
        $map = array();
        if (isset($_GET['content'])) {
            $map['content'] = array('like', '%' . (string) I('content') . '%');
        }
        if (isset($_GET['status'])) {
            $map['status'] = I('status');
            $status = $map['status'];
        } else {
            $status = null;
            $map['status'] = array('in', '0,1,2');
        }
        if (!isset($_GET['pid'])) {
            $map['pid'] = 0;
        }
        if (isset($_GET['time-start'])) {
            $map['update_time'][] = array('egt', strtotime(I('time-start')));
        }
        if (isset($_GET['time-end'])) {
            $map['update_time'][] = array('elt', 24 * 60 * 60 + strtotime(I('time-end')));
        }
        if (isset($_GET['username'])) {
            $map['uid'] = M('UcenterMember')->where(array('username' => I('username')))->getField('id');
        }

        // 構建列表數據
        $Document = M('Document');
        $map['category_id'] = $cate_id;
        $map['pid'] = I('pid', 0);
        if ($map['pid']) { // 子文檔列表忽略分類
            unset($map['category_id']);
        }

        $prefix = C('DB_PREFIX');
        $l_table = $prefix . ('document');
        $r_table = $prefix . ('document_article');
        $list = M()->table($l_table . ' l')
                ->where($map)
                ->order('l.id DESC')
                ->join($r_table . ' r ON l.id=r.id');
        $_REQUEST = array();
        $list = $this->lists($list, null, null, null, 'l.id id,l.pid pid,l.category_id,l.title title,l.update_time update_time,l.uid uid,l.status status,r.content content');
        int_to_string($list);

        if ($map['pid']) {
            // 獲取上級文檔
            $article = $Document->field('id,title,type')->find($map['pid']);
            $this->assign('article', $article);
        }
        //檢查該分類是否允許發布內容
        $allow_publish = get_category($cate_id, 'allow_publish');

        $this->assign('status', $status);
        $this->assign('list', $list);
        $this->assign('allow', $allow_publish);
        $this->assign('pid', $map['pid']);
        $this->meta_title = '子文檔列表';
        return 'reply'; //默認回復列表模板
    }

    /**
     * 默認文檔列表方法
     * @param $cate_id 分類id
     * @author huajie <banhuajie@163.com>
     */
    protected function indexOfArticle($cate_id) {
        /* 查詢條件初始化 */
        $map = array();
        if (isset($_GET['title'])) {
            $map['title'] = array('like', '%' . (string) I('title') . '%');
        }
        if (isset($_GET['status'])) {
            $map['status'] = I('status');
            $status = $map['status'];
        } else {
            $status = null;
            $map['status'] = array('in', '0,1,2');
        }
        if (!isset($_GET['pid'])) {
            $map['pid'] = 0;
        }
        if (isset($_GET['time-start'])) {
            $map['update_time'][] = array('egt', strtotime(I('time-start')));
        }
        if (isset($_GET['time-end'])) {
            $map['update_time'][] = array('elt', 24 * 60 * 60 + strtotime(I('time-end')));
        }
        if (isset($_GET['nickname'])) {
            $map['uid'] = M('Member')->where(array('nickname' => I('nickname')))->getField('uid');
        }

        // 構建列表數據
        $Document = M('Document');
        $map['category_id'] = $cate_id;
        $map['pid'] = I('pid', 0);
        if ($map['pid']) { // 子文檔列表忽略分類
            unset($map['category_id']);
        }

        $list = $this->lists($Document, $map, 'level DESC,id DESC');
        int_to_string($list);
        if ($map['pid']) {
            // 獲取上級文檔
            $article = $Document->field('id,title,type')->find($map['pid']);
            $this->assign('article', $article);
        }
        //檢查該分類是否允許發布內容
        $allow_publish = get_category($cate_id, 'allow_publish');

        $this->assign('status', $status);
        $this->assign('list', $list);
        $this->assign('allow', $allow_publish);
        $this->assign('pid', $map['pid']);

        $this->meta_title = '文檔列表';
        if($cate_id=="67"||$cate_id=='70'){
            return 'courselist';
        }else{            
            return 'index';
        }
    }
    /**
     * 设置会员通知
     */
    public function setNoticeStatus($model = 'Member_notice'){
         return parent::setStatus($model);
    }
    
    /**
     * 設置壹條或者多條數據的狀態
     * @author huajie <banhuajie@163.com>
     */
    public function setStatus($model = 'Document') {
        
        
        return parent::setStatus('Document');
    }
      /**
     * 設置壹條或者多條數據的狀態(自定義)
     * @author huajie <banhuajie@163.com>
     */
    public function setoStatus($model = 'Member_info') {
        return parent::setStatus('Member_info');
    }        
    /**
     * 文檔新增頁面初始化
     * @author huajie <banhuajie@163.com>
     */
    public function add() {
        //獲取左邊菜單
        $this->getMenu();
        $index = I('get.key',0);
        $cate_id = I('get.cate_id', 0);
        $model_id = I('get.model_id', 0);        
        empty($cate_id) && $this->error('參數不能為空！');
        empty($model_id) && $this->error('該分類未綁定模型！');

        //檢查該分類是否允許發布
        $allow_publish = D('Document')->checkCategory($cate_id);
        !$allow_publish && $this->error('該分類不允許發布內容！');

        /* 獲取要編輯的擴展模型模板 */
        $model = get_document_model($model_id);
        
        //處理結果
        $info['pid'] = $_GET['pid'] ? $_GET['pid'] : 0;
        $info['model_id'] = $model_id;
        $info['category_id'] = $cate_id;
        if ($info['pid']) {
            // 獲取上級文檔
            $article = M('Document')->field('id,title,type')->find($info['pid']);
            $this->assign('article', $article);
        }

        //獲取表單字段排序
        if ($model['id'] == 17) {
            $fields = get_model_attribute(17);  
            if($cate_id=="67"){
                $cate_ids=62;
            }elseif($cate_id=="70"){
                $cate_ids=63;
            }
            $course = D('Document')->lists($cate_ids);
                $courses = D('Document')->detail($course[$index]['id']);
                foreach($courses as $k=>$v){
                    if (strpos($v, ',')) {
                        $v = explode(",", $v);
                    } elseif (strpos($v, '，')) {
                        $v = explode("，", $v);
                    }
                    $courses[$k] = $v;
                }
            $this->assign('keys',$index);
            $this->assign('course',$course);
            $this->assign('courses',$courses);
            $this->assign('info', $info);
            $this->assign('fields', $fields);
            $this->assign('type_list', get_type_bycate($cate_id));
            $this->assign('model', $model);
            $this->meta_title = '新增' . $model['title'];
            $this->display('courseadd');
        } elseif ($model['id'] == 20) {
               $fields = get_model_attribute(20); 
               $instru=D('Document')->lists(52);
               foreach($instru as $ko=>$vo){
                   $instrus[]=D('Document')->detail($vo['id']);
               }
               $this->assign('instrus',$instrus);
               $this->assign('info', $info);
            $this->assign('fields', $fields);
            $this->assign('type_list', get_type_bycate($cate_id));
            $this->assign('model', $model);
            $this->meta_title = '新增' . $model['title'];
            $this->display('instruimaadd');
        }elseif ($model['id'] == 15) {
               $fields = get_model_attribute(15); 
               $house=D('Document')->lists(73);
               foreach($house as $ko=>$vo){
                   $houses[]=D('Document')->detail($vo['id']);
               }
               $this->assign('houses',$houses);
               $this->assign('info', $info);
            $this->assign('fields', $fields);
            $this->assign('type_list', get_type_bycate($cate_id));
            $this->assign('model', $model);
            $this->meta_title = '新增' . $model['title'];
            $this->display('rentadd');
        }else {
            $fields = get_model_attribute($model['id']);
            $this->assign('info', $info);            
            $this->assign('fields', $fields);
            $this->assign('type_list', get_type_bycate($cate_id));
            $this->assign('model', $model);
            $this->meta_title = '新增' . $model['title'];
            if ($model['template_add'] != " " || $model['template_add'] != "null") {

                $this->display($model['template_add']);
            } else {
                $this->display();
            }
        }
    }

    /**
     * 文檔編輯頁面初始化
     * @author huajie <banhuajie@163.com>
     */
    public function edit() {
        //獲取左邊菜單
        $this->getMenu();

        $id = I('get.id', '');
        if (empty($id)) {
            $this->error('參數不能為空！');
        }

        /* 獲取壹條記錄的詳細數據 */
        $Document = D('Document');
        $data = $Document->detail($id);
        if (!$data) {
            $this->error($Document->getError());
        }
        if ($data['pid']) {
            // 獲取上級文檔
            $article = M('Document')->field('id,title,type')->find($data['pid']);
            
           
            
            $this->assign('article', $article);
        }
        // dump( $data);
        $this->assign('data', $data);
        $this->assign('model_id', $data['model_id']);

        /* 獲取要編輯的擴展模型模板 */
        $model = get_document_model($data['model_id']);
        $this->assign('model', $model);
      
        //獲取表單字段排序
        if ($model['id'] == 17) {           
            if($data['category_id']=="67"){
                $cate_ids=62;
            }elseif($data['category_id']=="70"){
                $cate_ids=63;
            }
            $course = D('Document')->lists($cate_ids);
                $courses = D('Document')->detail($data['coursename']);
                foreach($courses as $k=>$v){
                    if (strpos($v, ',')) {
                        $v = explode(",", $v);
                    } elseif (strpos($v, '，')) {
                        $v = explode("，", $v);
                    }
                    $courses[$k] = $v;
                }
            $this->assign('course',$course);
            $this->assign('courses',$courses);
            //dump($course);
            //dump($courses);die;
            $fields = get_model_attribute(17);
            $this->assign('fields', $fields);
            $this->assign('type_list', get_type_bycate($data['category_id']));
            $this->meta_title = '編輯文檔';
            $this->display('courseedit');
        }elseif ($model['id'] == 20) {            
            $fields = get_model_attribute($model['id']);
            $instru=D('Document')->lists(52);
            foreach($instru as $ko=>$vo){
                   $instrus[]=D('Document')->detail($vo['id']);
               }
            $this->assign('instrus',$instrus);
            $this->assign('type_list', get_type_bycate($data['category_id']));
            $this->assign('fields', $fields);
            $this->meta_title = '編輯文檔';
            $this->display('instruimaedit');
        }elseif ($model['id'] == 15) {        
            
            
            $fields = get_model_attribute($model['id']);
            $house=D('Document')->lists(73);
               foreach($house as $ko=>$vo){
                   $houses[]=D('Document')->detail($vo['id']);
               }
               $this->assign('houses',$houses);
            $this->assign('type_list', get_type_bycate($data['category_id']));
            $this->assign('fields', $fields);
            $this->meta_title = '編輯文檔';
            $this->display('rentedit');
            
            
            
        }else{
            $fields = get_model_attribute($model['id']);
            $this->assign('fields', $fields);


            //獲取當前分類的文檔類型
            $this->assign('type_list', get_type_bycate($data['category_id']));

            $this->meta_title = '編輯文檔';
        if ($model['template_edit'] != " " || $model['template_edit'] != "null") {
           
          
            $this->display($model['template_edit']);
        } else {
            
            
            
            $this->display();
        }        
        }
    }

    //ajax查詢數組
    public function ajaxUrl(){
        $id=$_POST['id'];
        $courses=D('Document')->detail($id);
        foreach($courses as $k=>$v){
                    if (strpos($v, ',')) {
                        $v = explode(",", $v);
                    } elseif (strpos($v, '，')) {
                        $v = explode("，", $v);
                    }
                    $courses[$k] = $v;
                }
        $fields = get_model_attribute(17);
        $this->ajaxReturn($courses,'JSON');
//        dump($courses);die();
    }
    
    
    /**
     * 更新壹條數據
     * @author huajie <banhuajie@163.com>
     */
    public function update() {
           
        $address = I('post.address');
        $id = I('post.id');
          
        if(isset($address))
        {
               
             $map['address'] =  implode(",",$address);
             if(!$id)
             {   
            // M('Document_course')->add($map);
             }
             else
             {
              M('Document_course')->where(array('id'=>$id))->save($map);   
             }    
        }    
       $data = implode(",",$address);
        $res = D('Document')->update(null, $data);
        if (!$res) {
            $this->error(D('Document')->getError());
        } else {
            $this->success($res['id'] ? '更新成功' : '新增成功', Cookie('__forward__'));
        }
    }

    /**
     * 批量操作
     * @author huajie <banhuajie@163.com>
     */
    public function batchOperate() {
        //獲取左邊菜單
        $this->getMenu();

        $pid = I('pid', 0);
        $cate_id = I('cate_id');

        empty($cate_id) && $this->error('參數不能為空！');

        //檢查該分類是否允許發布
        $allow_publish = D('Document')->checkCategory($cate_id);
        !$allow_publish && $this->error('該分類不允許發布內容！');

        //批量導入目錄
        if (IS_POST) {
            $model_id = I('model_id');
            $type = 1; //TODO:目前只支持目錄，要動態獲取
            $content = I('content');
            $_POST['content'] = ''; //重置內容
            preg_match_all('/[^\r]+/', $content, $matchs); //獲取每壹個目錄的數據
            $list = $matchs[0];
            foreach ($list as $value) {
                if (!empty($value) && (strpos($value, '|') !== false)) {
                    //過濾換行回車並分割
                    $data = explode('|', str_replace(array("\r", "\r\n", "\n"), '', $value));
                    //構造新增的數據
                    $data = array('name' => $data[0], 'title' => $data[1], 'category_id' => $cate_id, 'model_id' => $model_id);
                    $data['description'] = '';
                    $data['pid'] = $pid;
                    $data['type'] = $type;
                    //構造post數據用於自動驗證
                    $_POST = $data;

                    $res = D('Document')->update($data);
                }
            }
            if ($res) {
                $this->success('批量導入成功！', U('index?pid=' . $pid . '&cate_id=' . $cate_id));
            } else {
                if (isset($res)) {
                    $this->error(D('Document')->getError());
                } else {
                    $this->error('批量導入失敗，請檢查內容格式！');
                }
            }
        }

        $this->assign('pid', $pid);
        $this->assign('cate_id', $cate_id);
        $this->assign('type_list', get_type_bycate($cate_id));

        $this->meta_title = '批量導入';
        $this->display('batchoperate');
    }

    /**
     * 待審核列表
     */
    public function examine() {
        //獲取左邊菜單
        $this->getMenu();

        $map['status'] = 2;
        if (!IS_ROOT) {
            $cate_auth = AuthGroupModel::getAuthCategories(UID);
            if ($cate_auth) {
                $map['category_id'] = array('IN', $cate_auth);
            } else {
                $map['category_id'] = -1;
            }
        }
        $list = $this->lists(M('Document'), $map, 'update_time desc');
        //處理列表數據
        if (is_array($list)) {
            foreach ($list as $k => &$v) {
                $v['username'] = get_nickname($v['uid']);
            }
        }

        $this->assign('list', $list);
        $this->meta_title = '待審核';
        $this->display();
    }

    /**
     * 課程預約
     */
    public function appointment() {
        $this->getMenu();

        if (!IS_ROOT) {
            $cate_auth = AuthGroupModel::getAuthCategories(UID);
            if ($cate_auth) {
                $map['category_id'] = array('IN', $cate_auth);
            } else {
                $map['category_id'] = -1;
            }
        }
        $list = M('appointment')->order('id desc')->select();
        $this->meta_title = '課程預約列表';
        $this->assign("list", $list);
        $this->meta_title = '課程預約';
        $this->display();
    }

    /**
     * 課程預約詳細頁
     */
    public function appointmentdetail(){
        $this->getMenu();
        $data['id']=$_GET['id'];
        $app=M('appointment')->where($data)->find();
        M('appointment')->where($data)->save(['readstatus'=>"已讀"]);
        $this->meta_title = '課程預約詳情';
        $this->assign('appoint',$app);
        $this->display();
    }
    
    /**
     * 留言板列表頁
     */
    public function fback() {
        //獲取左邊菜單
        $this->getMenu();
        $map['status'] = 1;
        if (!IS_ROOT) {
            $cate_auth = AuthGroupModel::getAuthCategories(UID);
            if ($cate_auth) {
                $map['category_id'] = array('IN', $cate_auth);
            } else {
                $map['category_id'] = -1;
            }
        }
        $this->meta_title = '反饋列表';
        $list = M('fback')->where($map)->order('id desc')->select();
        $this->assign("list", $list);
        $this->meta_title = '留言板';
        $this->display();
    }

    /**
     * 留言板詳情頁
     */
    public function fbackdetail(){
        $this->getMenu();
        $data['id']=$_GET['id'];
        $datas=M('fback')->where($data)->find();
        M('fback')->where($data)->save(array('read_status'=>"已讀"));    
        $this->meta_title = '留言詳情';
        $this->assign('data',$datas);
        $this->display();
        
    }
    public function del(){
        $data['id']=$_GET['id'];
        $datas=M('fback')->where($data)->delete(); 
        $this->success('刪除成功');
    }
    
    /**
     * 回收站列表
     * @author huajie <banhuajie@163.com>
     */
    public function recycle() {
        //獲取左邊菜單
        $this->getMenu();

        $map['status'] = -1;
        if (!IS_ROOT) {
            $cate_auth = AuthGroupModel::getAuthCategories(UID);
            if ($cate_auth) {
                $map['category_id'] = array('IN', $cate_auth);
            } else {
                $map['category_id'] = -1;
            }
        }
        $list = $this->lists(M('Document'), $map, 'update_time desc');

        //處理列表數據
        if (is_array($list)) {
            foreach ($list as $k => &$v) {
                $v['username'] = get_nickname($v['uid']);
            }
        }

        $this->assign('list', $list);
        $this->meta_title = '回收站';
        $this->display();
    }

    /**
     * 寫文章時自動保存至草稿箱
     * @author huajie <banhuajie@163.com>
     */
    public function autoSave() {
        $res = D('Document')->autoSave();
        if ($res !== false) {
            $return['data'] = $res;
            $return['info'] = '保存草稿成功';
            $return['status'] = 1;
            $this->ajaxReturn($return);
        } else {
            $this->error('保存草稿失敗：' . D('Document')->getError());
        }
    }

    /**
     * 草稿箱
     * @author huajie <banhuajie@163.com>
     */
    public function draftBox() {
        //獲取左邊菜單
        $this->getMenu();

        $Document = D('Document');
        $map = array('status' => 3, 'uid' => UID);
        $list = $this->lists($Document, $map);
        //獲取狀態文字
        //int_to_string($list);

        $this->assign('list', $list);
        $this->meta_title = '草稿箱';
        $this->display();
    }

    /**
     * 我的文檔
     * @author huajie <banhuajie@163.com>
     */
    public function mydocument($status = null, $title = null) {
        //獲取左邊菜單
        $this->getMenu();

        $Document = D('Document');
        /* 查詢條件初始化 */
        $map['uid'] = UID;
        if (isset($title)) {
            $map['title'] = array('like', '%' . $title . '%');
        }
        if (isset($status)) {
            $map['status'] = $status;
        } else {
            $map['status'] = array('in', '0,1,2');
        }
        if (isset($_GET['time-start'])) {
            $map['update_time'][] = array('egt', strtotime(I('time-start')));
        }
        if (isset($_GET['time-end'])) {
            $map['update_time'][] = array('elt', 24 * 60 * 60 + strtotime(I('time-end')));
        }
        //只查詢pid為0的文章
        $map['pid'] = 0;
        $list = $this->lists($Document, $map, 'update_time desc');
        int_to_string($list);
        // 記錄當前列表頁的cookie
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        $this->assign('status', $status);
        $this->assign('list', $list);
        $this->meta_title = '我的文檔';
        $this->display();
    }

    /**
     * 還原被刪除的數據
     * @author huajie <banhuajie@163.com>
     */
    public function permit() {
        /* 參數過濾 */
        $ids = I('param.ids');
        if (empty($ids)) {
            $this->error('請選擇要操作的數據');
        }

        /* 拼接參數並修改狀態 */
        $Model = 'Document';
        $map = array();
        if (is_array($ids)) {
            $map['id'] = array('in', $ids);
        } elseif (is_numeric($ids)) {
            $map['id'] = $ids;
        }
        $this->restore($Model, $map);
    }

    /**
     * 清空回收站
     * @author huajie <banhuajie@163.com>
     */
    public function clear() {
        $res = D('Document')->remove();
        if ($res !== false) {
            $this->success('清空回收站成功！');
        } else {
            $this->error('清空回收站失敗！');
        }
    }

    /**
     * 移動文檔
     * @author huajie <banhuajie@163.com>
     */
    public function move() {
        if (empty($_POST['ids'])) {
            $this->error('請選擇要移動的文檔！');
        }
        session('moveArticle', $_POST['ids']);
        session('copyArticle', null);
        $this->success('請選擇要移動到的分類！');
    }

    /**
     * 拷貝文檔
     * @author huajie <banhuajie@163.com>
     */
    public function copy() {
        if (empty($_POST['ids'])) {
            $this->error('請選擇要復制的文檔！');
        }
        session('copyArticle', $_POST['ids']);
        session('moveArticle', null);
        $this->success('請選擇要復制到的分類！');
    }

    /**
     * 粘貼文檔
     * @author huajie <banhuajie@163.com>
     */
    public function paste() {
        $moveList = session('moveArticle');
        $copyList = session('copyArticle');
        if (empty($moveList) && empty($copyList)) {
            $this->error('沒有選擇文檔！');
        }
        if (!isset($_POST['cate_id'])) {
            $this->error('請選擇要粘貼到的分類！');
        }
        $cate_id = I('post.cate_id'); //當前分類
        $pid = I('post.pid', 0);  //當前父類數據id
        //檢查所選擇的數據是否符合粘貼要求
        $check = $this->checkPaste(empty($moveList) ? $copyList : $moveList, $cate_id, $pid);
        if (!$check['status']) {
            $this->error($check['info']);
        }

        if (!empty($moveList)) {// 移動	TODO:檢查name重復
            foreach ($moveList as $key => $value) {
                $Model = M('Document');
                $map['id'] = $value;
                $data['category_id'] = $cate_id;
                $data['pid'] = $pid;
                //獲取root
                if ($pid == 0) {
                    $data['root'] = 0;
                } else {
                    $p_root = $Model->getFieldById($pid, 'root');
                    $data['root'] = $p_root == 0 ? $pid : $p_root;
                }
                $res = $Model->where($map)->save($data);
            }
            session('moveArticle', null);
            if (false !== $res) {
                $this->success('文檔移動成功！');
            } else {
                $this->error('文檔移動失敗！');
            }
        } elseif (!empty($copyList)) { // 復制
            foreach ($copyList as $key => $value) {
                $Model = M('Document');
                $data = $Model->find($value);
                unset($data['id']);
                unset($data['name']);
                $data['category_id'] = $cate_id;
                $data['pid'] = $pid;
                $data['create_time'] = NOW_TIME;
                $data['update_time'] = NOW_TIME;
                //獲取root
                if ($pid == 0) {
                    $data['root'] = 0;
                } else {
                    $p_root = $Model->getFieldById($pid, 'root');
                    $data['root'] = $p_root == 0 ? $pid : $p_root;
                }

                $result = $Model->add($data);
                if ($result) {
                    $logic = D(get_document_model($data['model_id'], 'name'), 'Logic');
                    $data = $logic->detail($value); //獲取指定ID的擴展數據
                    $data['id'] = $result;
                    $res = $logic->add($data);
                }
            }
            session('copyArticle', null);
            if ($res) {
                $this->success('文檔復制成功！');
            } else {
                $this->error('文檔復制失敗！');
            }
        }
    }

    /**
     * 檢查數據是否符合粘貼的要求
     * @author huajie <banhuajie@163.com>
     */
    protected function checkPaste($list, $cate_id, $pid) {
        $return = array('status' => 1);
        $Document = D('Document');

        // 檢查支持的文檔模型
        $modelList = M('Category')->getFieldById($cate_id, 'model'); // 當前分類支持的文檔模型
        foreach ($list as $key => $value) {
            //不能將自己粘貼為自己的子內容
            if ($value == $pid) {
                $return['status'] = 0;
                $return['info'] = '不能將編號為 ' . $value . ' 的數據粘貼為他的子內容！';
                return $return;
            }
            // 移動文檔的所屬文檔模型
            $modelType = $Document->getFieldById($value, 'model_id');

            if (!in_array($modelType, explode(',', $modelList))) {
                $return['status'] = 0;
                $return['info'] = '當前分類的文檔模型不支持編號為 ' . $value . ' 的數據！';
                return $return;
            }
        }

        // 檢查支持的文檔類型和層級規則
        $typeList = M('Category')->getFieldById($cate_id, 'type'); // 當前分類支持的文檔模型
        foreach ($list as $key => $value) {
            // 移動文檔的所屬文檔模型
            $modelType = $Document->getFieldById($value, 'type');
            if (!in_array($modelType, explode(',', $typeList))) {
                $return['status'] = 0;
                $return['info'] = '當前分類的文檔類型不支持編號為 ' . $value . ' 的數據！';
                return $return;
            }
            $res = $Document->checkDocumentType($modelType, $pid);
            if (!$res['status']) {
                $return['status'] = 0;
                $return['info'] = $res['info'] . '。錯誤數據編號：' . $value;
                return $return;
            }
        }

        return $return;
    }

    /**
     * 文檔排序
     * @author huajie <banhuajie@163.com>
     */
    public function sort() {
        if (IS_GET) {
            //獲取左邊菜單
            $this->getMenu();

            $ids = I('get.ids');
            $cate_id = I('get.cate_id');
            $pid = I('get.pid');

            //獲取排序的數據
            $map['status'] = array('gt', -1);
            if (!empty($ids)) {
                $map['id'] = array('in', $ids);
            } else {
                if ($cate_id !== '') {
                    $map['category_id'] = $cate_id;
                }
                if ($pid !== '') {
                    $map['pid'] = $pid;
                }
            }
            $list = M('Document')->where($map)->field('id,title')->order('level DESC,id DESC')->select();

            $this->assign('list', $list);
            $this->meta_title = '文檔排序';
            $this->display();
        } elseif (IS_POST) {
            $ids = I('post.ids');
            $ids = array_reverse(explode(',', $ids));
            foreach ($ids as $key => $value) {
                $res = M('Document')->where(array('id' => $value))->setField('level', $key + 1);
            }
            if ($res !== false) {
                $this->success('排序成功！');
            } else {
                $this->eorror('排序失敗！');
            }
        } else {
            $this->error('非法請求！');
        }
    }

    public function userlist() {
        if (!IS_ROOT) {
            $cate_auth = AuthGroupModel::getAuthCategories(UID);
            if ($cate_auth) {
                $map['category_id'] = array('IN', $cate_auth);
            } else {
                $map['category_id'] = -1;
            }
        }
        //獲取左邊菜單
        $this->getMenu();
        $nickname = I('nickname');
        $map['status'] = array('eq', 2);
        if (is_numeric($nickname)) {
            $map['id|username'] = array(intval($nickname), array('like', '%' . $nickname . '%'), '_multi' => true);
        } else {
            $map['username'] = array('like', '%' . (string) $nickname . '%');
        }
        $list = $this->lists('ucenter_member', $map);

        int_to_string($list);
        $this->assign('list', $list);
        $this->meta_title = '會員信息';
        $this->display();
    }

    public function useradd() {
        //獲取左邊菜單
        $this->getMenu();
        $this->display();
    }

    public function useredit() {
        if ($_POST) {
             $User = new UserApi; 
             $password= think_ucenter_md5($_POST['password'], '4T(:0Yt_"X`c~I$96mu]EG.pVhy?nxL>#<1s2Ae8');           
             $map['id']=$_POST['id'];
             $data = array(
                'password' =>$password,
                'mobile' => $_POST['phone'],
                'email' => $_POST['email'],
                'address' => $_POST['address'],
            );
            if (empty($data['password']))
                unset($data['password']);

            $id = M('Ucenter_member')->where($map)->save($data);
           
            if ($id) {
                $this->success("更新成功", U('Admin/Article/userlist'));
            } else {
                $this->error("更新失敗");
            }
        } else {
            //獲取左邊菜單
            $this->getMenu();
            $map['id'] = $_GET['uid'];
            $map['status'] = array('eq', 2);
            $list = $this->lists('ucenter_member', $map);
            int_to_string($list);
            $this->assign('list', $list);
            $this->meta_title = '編輯會員信息';
            $this->display();
        }
    }

    //刪除會員
    public function userdel() {
        $map = array(
            'id' => I('id'),
        );
        $id = M('Ucenter_member')->where($map)->delete();
        if ($id) {
            $this->success("刪除成功", U('Admin/Article/userlist'));
        } else {
            $this->error("刪除失敗");
        }
    }
   //删除
   public function cdel(){
       
      $id = I('get.id');
      
      if(!empty($id))
      {    
      $data = M('Document')->where(["id"=>$id])->delete();
      $data2= M('Document_courselist')->where(["id"=>$id])->delete();
      if($data&&$data2)
      {
          $this->success("删除成功");
                  
      }
      else
      {
        $this->error("操作失败");
                    
      }    
      }  
   }
     //删除
   public function adel(){
       
      $id = I('get.id');
      
      if(!empty($id))
      {    
      $data2= M('appointment')->where(["id"=>$id])->delete();
      if($data2)
      {
          $this->success("删除成功");
                  
      }
      else
      {
        $this->error("操作失败");
                    
      }    
      }  
   }
}